package com.aididi.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * @Auther: zx.xu
 * @Description:
 */
@RestController
@RequestMapping("/rb")
@Slf4j
public class ConsumerController {

    @Value("${spring.application.name}")
    String serverName;

    @Autowired
    private LoadBalancerClient loadBalancerClient;

    @Autowired
    private RestTemplate restTemplate;


    @GetMapping("/test/hello")
    public String echoAppName(){
        //使用 LoadBalanceClient 和 RestTemplate 结合的方式来访问
        //ServiceInstance serviceInstance = loadBalancerClient.choose("nacos-provider");
        //String url = String.format("http://%s:%s/test/%s",serviceInstance.getHost(),serviceInstance.getPort(),serverName);
        //采用负载均衡的方式
        String url = String.format("http://%s/test/%s","nacos-provider",serverName);
        log.info("request url:{}",url);
        return restTemplate.getForObject(url,String.class);
    }

}
